/*
 * ExplorerList.java
 *
 * Created on February 27, 2006, 8:32 PM
 */
package com.bff.slimserver.musicjukebox.ui;

import com.bff.bjj.ui.component.events.KeyTypedEvent;
import com.bff.bjj.ui.component.events.KeyTypedListener;
import com.bff.bjj.utils.Utils;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.ui.components.AlbumList;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.slimserver.musicjukebox.ui.components.YearList;
import java.awt.Container;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bff.slimserver.SlimDatabase;
import org.bff.slimserver.SlimPlaylist;
import org.bff.slimserver.events.DatabaseScanEvent;
import org.bff.slimserver.events.DatabaseScanListener;

/**
 *
 * @author  Bill
 */
public class YearPanel
        extends BJJPanel
        implements ExplorerIface,
        KeyTypedListener,
        DatabaseScanListener {

    private SlimPlaylist playlist;
    private SlimDatabase database;
    private boolean refreshing;
    private Container parent;
    private int oldSelectedYearIndex;
    private int oldSelectedAlbumIndex;
    private boolean threadRunning;
    private boolean keyTyped;

    public YearPanel() {
    }

    /** Creates new form ExplorerList */
    public YearPanel(SlimDatabase database, SlimPlaylist playlist) {
        this.database = database;
        this.playlist = playlist;
        this.parent = this;

        initComponents();

        listYears();

//        getAlbumJList().setArtist(getArtistJList().getSelectedArtist());
        //       getArtistJList().addKeyTypedListener(this);

        listSongs();

        loadProgressBar.setVisible(false);
        
        JukeboxProperties.getInstance().getSlimMonitor().addDatabaseScanListener(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel3 = new BJJPanel();
        songListTablePanel = new SongListTablePanel();
        jPanel4 = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel1 = new BJJPanel();
        spYear = new javax.swing.JScrollPane();
        yearList = new YearList();
        jPanel2 = new BJJPanel();
        spAlbum = new javax.swing.JScrollPane();
        albumList = new AlbumList();
        loadProgressBar = new javax.swing.JProgressBar();

        setPreferredSize(new java.awt.Dimension(400, 400));
        setLayout(new java.awt.BorderLayout());

        jSplitPane1.setDividerLocation(500);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)));
        jPanel3.setPreferredSize(new java.awt.Dimension(200, 200));
        jPanel3.setLayout(new java.awt.BorderLayout());

        songListTablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Songs"));
        jPanel3.add(songListTablePanel, java.awt.BorderLayout.CENTER);

        jSplitPane1.setBottomComponent(jPanel3);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Year"));
        jPanel1.setMinimumSize(new java.awt.Dimension(200, 59));
        jPanel1.setLayout(new java.awt.BorderLayout());

        yearList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        yearList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                yearListValueChanged(evt);
            }
        });
        spYear.setViewportView(yearList);

        jPanel1.add(spYear, java.awt.BorderLayout.CENTER);

        jSplitPane2.setLeftComponent(jPanel1);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Album"));
        jPanel2.setLayout(new java.awt.BorderLayout());

        albumList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        albumList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                albumListValueChanged(evt);
            }
        });
        spAlbum.setViewportView(albumList);

        jPanel2.add(spAlbum, java.awt.BorderLayout.CENTER);

        loadProgressBar.setIndeterminate(true);
        loadProgressBar.setString("Loading Albums");
        loadProgressBar.setStringPainted(true);
        jPanel2.add(loadProgressBar, java.awt.BorderLayout.SOUTH);

        jSplitPane2.setRightComponent(jPanel2);

        jPanel4.add(jSplitPane2, java.awt.BorderLayout.CENTER);

        jSplitPane1.setLeftComponent(jPanel4);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void yearListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_yearListValueChanged
        if (getYearJList().getSelectedIndex() != oldSelectedYearIndex) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    if (!isRefreshing()) {
                        loadProgressBar.setVisible(true);
                        yearList.setEnabled(false);
                        try {
                            getAlbumJList().setYear(getYearJList().getSelectedYear());
                            getAlbumJList().setSelectedIndex(1);
                            jPanel2.revalidate();
                        } finally {
                            loadProgressBar.setVisible(false);
                            yearList.setEnabled(true);
                        }
                        listSongs();
                    }
                    oldSelectedYearIndex = getYearJList().getSelectedIndex();
                }
            }).start();
        }
}//GEN-LAST:event_yearListValueChanged

    private void albumListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_albumListValueChanged
        if (getAlbumJList().getSelectedIndex() > -1 && getAlbumJList().getSelectedIndex() != oldSelectedAlbumIndex) {
            if (!isRefreshing()) {
                getSongListTablePanel().setProgressBarVisible(true);
                albumList.setEnabled(false);
                yearList.setEnabled(false);
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            listSongs();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            getSongListTablePanel().setProgressBarVisible(false);
                            albumList.setEnabled(true);
                            yearList.setEnabled(true);
                        }
                    }
                }).start();


            }
            oldSelectedAlbumIndex = getAlbumJList().getSelectedIndex();
        }
}//GEN-LAST:event_albumListValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList albumList;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JProgressBar loadProgressBar;
    private javax.swing.JPanel songListTablePanel;
    private javax.swing.JScrollPane spAlbum;
    private javax.swing.JScrollPane spYear;
    private javax.swing.JList yearList;
    // End of variables declaration//GEN-END:variables

    public void refreshComponents() {
        setRefreshing(true);
        listYears();
        setRefreshing(false);
    }

    private synchronized void listSongs() {

        while (isThreadRunning()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Logger.getLogger(YearPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        new ListSongThread().start();
    }

    public boolean isRefreshing() {
        return refreshing;
    }

    public void setRefreshing(boolean refreshing) {
        this.refreshing = refreshing;
    }

    private void listYears() {
        getYearJList().listAll();
    }

    public SlimDatabase getDatabase() {
        return database;
    }

    public void setDatabase(SlimDatabase database) {
        this.database = database;
    }

    public SlimPlaylist getPlaylist() {
        return playlist;
    }

    public void setPlaylist(SlimPlaylist playlist) {
        this.playlist = playlist;
    }

    private YearList getYearJList() {
        return (YearList) yearList;
    }

    private SongListTablePanel getSongListTablePanel() {
        return (SongListTablePanel) songListTablePanel;
    }

    public boolean isThreadRunning() {
        return threadRunning;
    }

    public void setThreadRunning(boolean threadRunning) {
        this.threadRunning = threadRunning;
    }

    public boolean isKeyTyped() {
        return keyTyped;
    }

    public void setKeyTyped(boolean keyTyped) {
        this.keyTyped = keyTyped;
    }

    private class ListSongThread extends Thread {

        ListSongThread() {
        }

        @Override
        public void run() {
            setThreadRunning(true);
            try {
                if (!isKeyTyped()) {
                    getSongListTablePanel().setProgressBarVisible(true);
                    albumList.setEnabled(false);
                    yearList.setEnabled(false);

                    try {
                        if (yearList.getSelectedIndex() > -1) {
                            if (yearList.getSelectedIndex() == 0 && getAlbumJList().getModel().getSize() > 1) {
                                getSongListTablePanel().setSongs(getDatabase().listSongsForYear(getYearJList().getSelectedYear()));
                            } else {
                                if (getAlbumJList().getSelectedAlbum() != null) {
                                    getSongListTablePanel().setAlbum(getAlbumJList().getSelectedAlbum());
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        getSongListTablePanel().setProgressBarVisible(false);
                        albumList.setEnabled(true);
                        yearList.setEnabled(true);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            setThreadRunning(false);
        }
    }

    @Override
    public void keyTyped(KeyTypedEvent event) {
        switch (event.getId()) {
            case TYPE_STARTED:
                setKeyTyped(true);
                break;
            default:
                setKeyTyped(false);
                if (event.isChange()) {
                    listSongs();
                }
                break;
        }

    }

    private AlbumList getAlbumJList() {
        return (AlbumList) albumList;
    }

    @Override
    public void databaseScanEventReceived(DatabaseScanEvent event) {
        if (event.getId() == DatabaseScanEvent.SCAN_ENDED) {
            final SplashScreen sp = new SplashScreen(Utils.getParentComponent(this), true);

            sp.setIndeterminate(true);
            sp.setTitleLabel("Reloading");
            sp.setMainTextArea("\nReloading Artists after database scan.\n\n");
            sp.setProgressBarLabel("Reloading...");
            sp.pack();

            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        getYearJList().listAll();
                    } finally {
                        sp.setStopped(true);
                    }
                }
            });
            t.start();

        }
    }
}
